package com.br.aiops.alert;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Component
public class FreemarkerUtils {

    public static final String TEMPLATE_NAME = "alertTemplate";

    public Optional<String> generatorHTML(String templateContent, Map<String, Object> params) {
        Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        try {
            StringTemplateLoader templateLoader = new StringTemplateLoader();
            templateLoader.putTemplate(TEMPLATE_NAME, templateContent);
            cfg.setTemplateLoader(templateLoader);

            //加载具体模板文件，得到模板对象
            Template template = cfg.getTemplate(TEMPLATE_NAME);
            //编码格式
            cfg.setDefaultEncoding("utf-8");

            Writer out = new StringWriter();
            //生成文件
            template.process(params, out);
            out.close();
            return Optional.of(out.toString());
        } catch (Exception e) {
            log.error("生成模板失败。", e);
        }
        return Optional.empty();
    }
}
